<?php

$lDb = new PDO('mysql:host=localhost;dbname=wswstats', 'wswstats', 'wswstats');

if ($_GET['q'] != 'chart') :
$lTime0 = microtime(true);

if (!isset($_GET['matchID'])) {
	$lLatestMatch = $lDb->query('SELECT MAX(matchID) FROM event WHERE type="end" AND actor="game"');
	$lMatchID = $lLatestMatch->fetch();
	$lMatchID = $lMatchID[0];
} else {
	$lMatchID = $_GET['matchID'];
}

$lMatchHistoryRes = $lDb->query('SELECT matchID FROM event WHERE type="end"');
$lMatchHistory = array();
foreach ($lMatchHistoryRes as $lMatchHistoryEntry) {
	$lMatchHistory[] = $lMatchHistoryEntry[0];
}
$lCurrentIndex = array_search($lMatchID, $lMatchHistory);

$lWhere = ' AND matchID="'.$lMatchID.'"';

$lMap = $lDb->query('SELECT actor,date FROM event WHERE type="spawn"'.$lWhere);
$lGame = $lMap->fetch();

$lEnd = $lDb->query('SELECT actor FROM event WHERE type="end"'.$lWhere);
$lGameType = $lEnd->fetch();

$lStart = $lDb->query('SELECT date FROM event WHERE type="starting"'.$lWhere);
$lStart = $lStart->fetchColumn(0);
$lEnd = $lDb->query('SELECT date FROM event WHERE type="end"'.$lWhere);
$lEnd = $lEnd->fetchColumn(0);

$lTeams = $lDb->query('SELECT actor,subject FROM event WHERE type="team"'.$lWhere.' ORDER BY date ASC');
$mTeams = array();
foreach ($lTeams as $lActor) {
	$mTeams[$lActor[0]] = $lActor[1];
}

$lPlayers0 = $lDb->query('SELECT DISTINCT(actor) FROM event WHERE type="team" '.$lWhere);
$lPlayers = array();
foreach ($lPlayers0 as $lPlayer) {
	$lPlayers []= $lPlayer[0];
}

$lWhere .= ' AND date >= "'.$lStart.'" AND date <= "'.$lEnd.'"';

$lEvents = $lDb->query(
'SELECT type AS lType, COUNT(*) AS lTotal'.
',(SELECT COUNT(*) FROM event WHERE type=lType'.$lWhere.' GROUP BY actor ORDER BY COUNT(*) DESC LIMIT 1) AS lTotalTop'.
',(SELECT actor FROM event WHERE type=lType'.$lWhere.' GROUP BY actor ORDER BY COUNT(*) DESC LIMIT 1) AS lTop'.
' FROM event WHERE type NOT IN ("spawn", "kill", "starting", "end", "team") '.$lWhere.' GROUP BY type'
);

$lCaptures = $lDb->query('SELECT actor FROM event WHERE type="Flag Capture!"'.$lWhere);
$lScore = array();
$lScore['ALPHA'] = 0;
$lScore['BETA'] = 0;
foreach ($lCaptures as $lCapture) {
	++$lScore[$mTeams[$lCapture[0]]];
}

$lKills = $lDb->query(
'SELECT subject AS lKiller, COUNT(*) AS totalKill'.
',(SELECT actor FROM event WHERE subject=lKiller AND type="kill"'.$lWhere.' GROUP BY actor ORDER BY COUNT(*) DESC LIMIT 1) AS lFavorite'.
',(SELECT COUNT(*) AS nbKills FROM event WHERE subject=lKiller AND type="kill"'.$lWhere.' GROUP BY actor ORDER BY nbKills DESC LIMIT 1) AS lMaxKills'.
' FROM event WHERE subject<>"" AND type="kill" '.$lWhere.' GROUP BY subject ORDER BY totalKill DESC');

$lKilled = $lDb->query(
'SELECT actor AS lActor, COUNT(*) AS totalKill'.
',(SELECT subject FROM event WHERE actor=lActor AND type="kill"'.$lWhere.' GROUP BY subject ORDER BY COUNT(*) DESC LIMIT 1) AS lNightmare'.
',(SELECT COUNT(*) AS nbKills FROM event WHERE actor=lActor AND type="kill"'.$lWhere.' GROUP BY subject ORDER BY nbKills DESC LIMIT 1) AS lMaxKills'.
' FROM event WHERE actor<>"" AND type="kill" '.$lWhere.' GROUP BY actor ORDER BY totalKill DESC');

$lTime1 = microtime(true);

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
<?php 
foreach ($lPlayers as $lPlayer) {
	echo 'swfobject.embedSWF("open-flash-chart.swf", "chart-'.$lPlayer.'", "550", "200", "9.0.0", "expressInstall.swf", {"data-file":"'.urlencode('data.php?player='.$lPlayer.'&q=chart').'"} );'."\n";
}
?>
</script>
</head>
<body>
<h1>Match statistics (<?php echo $lGameType[0]; ?>/<?php echo $lGame[0]; ?>/<?php echo $lGame[1]; ?>)</h1>
<?php 
if (($lCurrentIndex - 1) >= 0) {
	echo '<a href="?matchID='.($lMatchHistory[$lCurrentIndex - 1]).'">Previous match</a> ';
}
if (($lCurrentIndex + 1) < count($lMatchHistory)) {
	echo '<a href="?matchID='.($lMatchHistory[$lCurrentIndex + 1]).'">Next match</a> ';
}
?>
<div class="left">
<h2>Teams</h2>
<div class="team-ALPHA">
<h3>Alpha (<?php echo $lScore['ALPHA']; ?>)</h3>
<?php
	foreach ($mTeams as $lActor => $lTeam) {
		if ($lTeam == 'ALPHA') {
			echo $lActor."<br/>\n";
		}
	} ?>
</div>
<div class="team-BETA">
<h3>Beta (<?php echo $lScore['BETA']; ?>)</h3>
<?php
	foreach ($mTeams as $lActor => $lTeam) {
		if ($lTeam == 'BETA') {
			echo $lActor."<br/>\n";
		}
	} ?>
</div>
<br class="clear"/>
</div>
<div class="right">
<h2>Events</h2>
<table border='1'><tr><th>Event</th><th># (total)</th><th>top player</th><th># (top player)</th></tr>
<?php
foreach($lEvents as $lEvent) {
	echo '<tr><td>'.$lEvent['lType'].'</td><td>'.$lEvent['lTotal'].'</td><td class="team-'.$mTeams[$lEvent['lTop']].'">'.$lEvent['lTop'].'</td><td class="team-'.$mTeams[$lEvent['lTop']].'">'.$lEvent['lTotalTop'].'</td></tr>'."\n";
}
?>
</table>
</div>
<br class="clear"/>
<div class="left">
<h2>Kills</h2>
<table border='1'><tr><th>Player</th><th># (total)</th><th>favorite target</th><th># (favorite target)</th></tr>
<?php
foreach($lKills as $lKill) {
	echo '<tr class="team-'.$mTeams[$lKill['lKiller']].'"><td>'.$lKill['lKiller'].'</td><td>'.$lKill['totalKill'].'</td><td>'.$lKill['lFavorite'].'</td><td>'.$lKill['lMaxKills'].'</td></tr>'."\n";
}
?>
</table>
</div>
<div class="right">
<h2>Killed</h2>
<table border='1'><tr><th>Player</th><th># (total)</th><th>nightmare</th><th># (nightmare)</th></tr>
<?php
foreach($lKilled as $lKill) {
	echo '<tr class="team-'.$mTeams[$lKill['lActor']].'"><td>'.$lKill['lActor'].'</td><td>'.$lKill['totalKill'].'</td><td>'.$lKill['lNightmare'].'</td><td>'.$lKill['lMaxKills'].'</td></tr>'."\n";
}
?>
</table>
</div>
<br class="clear"/>
<?php 
foreach ($lPlayers as $lPlayer) {
	echo '<div id="chart"><h2>'.$lPlayer."</h2>\n";
	echo '<div id="chart-'.$lPlayer.'"></div>'."\n";
	echo '</div>'."\n";
}
?>
<?php 
echo sprintf("%.3f", ($lTime1 - $lTime0))."s to generate<br/>";
?>
</body>
</html>
<?php
else :

include 'php-ofc-library/open-flash-chart.php';

$lPlayer = $_GET['player'];
$lWhere = ' AND type="end"';

$lKills = $lDb->query(
'SELECT DISTINCT(matchID) AS lMatchID'.
',(SELECT COUNT(*) AS totalKill FROM event WHERE subject="'.$lPlayer.'" AND type="kill" AND matchID=lMatchID)'.
' FROM event WHERE 1 '.$lWhere.' GROUP BY matchID ORDER BY matchID ASC');

$lKilled = $lDb->query(
'SELECT DISTINCT(matchID) AS lMatchID'.
',(SELECT COUNT(*) AS totalKill FROM event WHERE actor="'.$lPlayer.'" AND type="kill" AND matchID=lMatchID)'.
' FROM event WHERE 1 '.$lWhere.' GROUP BY matchID ORDER BY matchID ASC');

$lCaptured = $lDb->query(
'SELECT DISTINCT(matchID) AS lMatchID'.
',(SELECT COUNT(*) AS totalKill FROM event WHERE actor="'.$lPlayer.'" AND type="Flag Capture!" AND matchID=lMatchID)'.
' FROM event WHERE 1 '.$lWhere.' GROUP BY matchID ORDER BY matchID ASC');

$lMax = 0;

$lKillsArray = array();
foreach ($lKills as $lEvent) {
	$lKillsArray[] = (int)($lEvent[1]);
	$lMax = max($lMax, $lEvent[1]);
}

$lKilledArray = array();
foreach ($lKilled as $lEvent) {
	$lKilledArray[] = (int)($lEvent[1]);
	$lMax = max($lMax, $lEvent[1]);
}

$lCapturedArray = array();
foreach ($lCaptured as $lEvent) {
	$lCapturedArray[] = (int)($lEvent[1]);
	$lMax = max($lMax, $lEvent[1]);
}

$chart = new open_flash_chart();

$title = new title( $lPlayer );
$chart->set_title( $title );

$y_axis = new y_axis();
$y_axis->set_range( 0, $lMax, 20 );
$y_axis->labels = null;
$y_axis->set_offset( false );
$chart->add_y_axis( $y_axis );

$x = new x_axis();
$x->set_steps( 2 );
$chart->set_x_axis( $x );

$lKillLine = new line();
$lKillLine->set_key('kills', 10);
$lKillLine->set_values( $lKillsArray );
$lKillLine->set_colour( '#0000ff' );
$chart->add_element( $lKillLine );

$lKilledLine = new line();
$lKilledLine->set_key('killed', 10);
$lKilledLine->set_values( $lKilledArray );
$lKilledLine->set_colour( '#ff0000' );
$chart->add_element( $lKilledLine );

$lCapturedLine = new line();
$lCapturedLine->set_key('captured', 10);
$lCapturedLine->set_values( $lCapturedArray );
$lCapturedLine->set_colour( '#00ff00' );
$chart->add_element( $lCapturedLine );

echo $chart->toString();

endif;
?>
